package com.emm.yixun.mobile.ui

import android.os.Bundle
import android.view.View
import com.emm.yixun.mobile.R
import com.emm.yixun.mobile.api.firstContact.FirstContactService
import com.emm.yixun.mobile.application.Constant
import com.emm.yixun.mobile.application.EmmApplication
import com.emm.yixun.mobile.base.BaseActivity
import com.emm.yixun.mobile.customview.BottomSheet
import com.emm.yixun.mobile.http.RetrofitFactory
import com.emm.yixun.mobile.model.*
import com.emm.yixun.utils.CommonUtils
import com.emm.yixun.utils.ToastUtils
import com.google.gson.Gson
import com.lidroid.xutils.util.LogUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function3
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_first_contact.*
import kotlinx.android.synthetic.main.main_head_title.*
import me.imid.swipebacklayout.lib.app.SwipeBackActivity
import xf.tools.Loading

class FirstContactActivity : SwipeBackActivity() {

    companion object {
        const val CUSTOMER = "CUSTOMER"
    }

    lateinit var customer: GetCustomerList.CustomerList

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first_contact)
        init()
    }

    private fun init() {
        BaseActivity.activity = this
        SetSwipeBackLayout(null)
        SetRelativiLayoutPadding(R.id.main_head_top_rela)
        customer = intent.getSerializableExtra(CUSTOMER) as GetCustomerList.CustomerList
        initViews()
    }

    private fun initViews() {
        title_main.text = "首次接触信息"
        back_btn.setOnClickListener { finish() }
        iv_call.setOnClickListener { call(customer.mobile) }
        tv_name.text = customer.customerName
        iv_star.visibility = if (customer.star == "1") View.VISIBLE else View.GONE
        tv_sex.text = if (customer.customerSex == "1") "男" else "女"
        tv_level.text = customer.intentionLevel
        tv_come_status.text = customer.customerOrigin
        tv_sign_status.text = customer.customerStatus
        tv_phone.text = customer.mobile
        initData()
    }

    private fun initData() {
        Loading.showDialogForLoading(this, "正在加载……", false, true, 30000)
        val contactObservable = RetrofitFactory.createService(FirstContactService::class.java)
                .getContactWay(Gson().toJson(Params(GetContactWayParams(
                        CommonUtils.version,
                        EmmApplication.getData(EmmApplication.merchantId),
                        EmmApplication.getToken(),
                        EmmApplication.getUserId(),
                        EmmApplication.getProjectCode(),
                        EmmApplication.getProjectID(),
                        EmmApplication.getPackageManager(2),
                        customer.customerId
                ))))
        val dictionaryObservable = RetrofitFactory.createService(FirstContactService::class.java)
                .getDictionaryList(Gson().toJson(Params(GetDictionaryParams(
                        CommonUtils.version,
                        EmmApplication.getPackageManager(2),
                        EmmApplication.getData(EmmApplication.merchantId),
                        EmmApplication.getProjectID(),
                        "01", "11", "1"
                ))))
        val dateObservable = RetrofitFactory.createService(FirstContactService::class.java)
                .getServerTime()
        Observable.zip(contactObservable, dictionaryObservable, dateObservable,
                Function3<Result<ContactWayBean>, Result<DictionaryList>, Result<ServerTimeBean>, AllData>
                { t1, t2, t3 -> AllData(t1, t2, t3)})
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    onGetFirstContact(it.contactWay.resData, it.dictionary.resData, it.serverTime.resData)
                }, {
                    onError(it)
                })

    }

    private fun onGetFirstContact(data: ContactWayBean, dictionary: DictionaryList, serverTime: ServerTimeBean) {
        Loading.hideDialogForLoading()
        LogUtils.d(data.toString())
        if (data.result == Constant.SUCCESS && dictionary.result == Constant.SUCCESS && serverTime.result == Constant.SUCCESS) {
            if (!data.ftContactWay.isNullOrBlank()) {          //有首次来电
                tv_contact_way.text = data.ftContactWayName
                tv_contact_date.text = data.ftContactTime
                tv_phone_content.text = data.ftContactContent
                if (data.ftContactWay1.isNullOrBlank()) {     //如果没有首次来访，就可以编辑
                    enableEdit(dictionary, serverTime)
                } else {                                      //有首次来访，不可编辑
                    setVisitData(data)
                }
            } else {                                          //没有首次来电，必然有首次来访
                rl_contact_way.visibility = View.GONE
                rl_contact_date.visibility = View.GONE
                ll_communication_content.visibility = View.GONE
                separator_contact_way.visibility = View.GONE
                separator_contact_date.visibility = View.GONE
                separator_part.visibility = View.GONE
                setVisitData(data)
            }
        } else {
            btn_save.visibility = View.GONE
            ToastUtils.showToast("服务器异常：${data.errorMsg}${dictionary.errorMsg}${serverTime.errorMsg}")
        }
    }

    private fun enableEdit(ways: DictionaryList, serverTime: ServerTimeBean) {
        var position = -1
        rl_contact_way1.setOnClickListener { _ ->
            BottomSheet().let {
                it.data = ways.rqBusNumList.map { data -> data.dictionaryName }
                it.listener = { index ->
                    position = index
                    tv_contact_way1.text = it.data[index]
                }
                it.show(supportFragmentManager, "contactWay")
            }
        }
        tv_contact_date1.text = serverTime.serverTime.substring(0, 11)
        et_come_content.run {
            isFocusable = true
            isFocusableInTouchMode = true
            requestFocus()
        }
        btn_save.setOnClickListener {
            updateFirstContact(position, ways, serverTime.serverTime)
        }
    }

    private fun disableEdit() {
        rl_contact_way1.setOnClickListener { }
        et_come_content.run {
            isFocusable = false
            isFocusableInTouchMode = false
        }
        btn_save.visibility = View.GONE
    }

    private fun setVisitData(data: ContactWayBean) {
        btn_save.visibility = View.GONE
        tv_contact_way1.text = data.ftContactWayName1
        tv_contact_date1.text = data.ftContactTime1
        et_come_content.setText(data.ftContactContent1, null)
        btn_save.visibility = View.GONE
    }

    private fun updateFirstContact(position: Int, ways: DictionaryList, date: String) {
        val content = et_come_content.text.toString()
        if (position != -1 && content.isNotEmpty()) {
            Loading.showDialogForLoading(this, "正在更新首触信息……", false, true, 30000)
            RetrofitFactory.createService(FirstContactService::class.java)
                    .addContactWay(Gson().toJson(Params(AddContactWayParams(
                            CommonUtils.version,
                            EmmApplication.getData(EmmApplication.merchantId),
                            EmmApplication.getToken(),
                            EmmApplication.getUserId(),
                            EmmApplication.getProjectCode(),
                            EmmApplication.getProjectID(),
                            EmmApplication.getPackageManager(2),
                            customer.customerId,
                            null, null, null,
                            ways.rqBusNumList[position].dictionaryId, date, content
                    ))))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Loading.hideDialogForLoading()
                        if (it.resData.result == Constant.SUCCESS) {
                            disableEdit()
                            ToastUtils.showToast("保存成功")
                        } else {
                            ToastUtils.showToast("保存失败${it.resData.errorMsg}")
                        }
                    }, {
                        onError(it)
                    })
        } else {
            ToastUtils.showToast("请选择接触方式和沟通内容后再保存～")
        }
    }
}

data class AllData(
        val contactWay: Result<ContactWayBean>,
        val dictionary: Result<DictionaryList>,
        val serverTime: Result<ServerTimeBean>
)
